package xyz.syyrjx.controller;

import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import xyz.syyrjx.entity.ResultInfo;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.Wan
 * @date 2022/10/12 - 21:26
 */
@Controller
public class RedisBalckController {
    private final static String BLACK_LIST = "black";
    private final static String BLACK_COUNT = "blackCount";

    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("/black/exists")
    public ResultInfo<String> isInBlack(@RequestParam String identity){
        System.out.println("isInbalck");
        try {
            if(redisTemplate.opsForSet().isMember(BLACK_LIST,identity)){
                return ResultInfo.success("在黑名单中");
            }
            return ResultInfo.fail("不在黑名单中");
        }catch (Exception e){
            return ResultInfo.fail(e.getMessage());
        }
    }

    @RequestMapping("black/add")
    public ResultInfo<String> blackAdd(@RequestParam String ip){
        try {
            Long add = redisTemplate.opsForSet().add(BLACK_LIST, ip);
            if (add > 0) {
                return ResultInfo.success("黑名单添加成功");
            } else {
                return ResultInfo.fail("黑名单添加失败");
            }
        }catch (Exception e){
            return ResultInfo.fail(e.getMessage());
        }
    }


    @RequestMapping("black/count")
    public ResultInfo<Long> blackCount(@RequestParam String ip) {
        try {
            ValueOperations valueOperations = redisTemplate.opsForValue();
            Object obj = valueOperations.get(ip);
            if (null == obj) {
                valueOperations.set(ip, 1, 500L, TimeUnit.MILLISECONDS);
                return ResultInfo.success(1L);
            } else {
                long count = valueOperations.increment(ip);
                return ResultInfo.success(count);
            }
        }catch (Exception e){
            return ResultInfo.fail("ip请求记录失败");
        }
    }
}
